/*
 * Copyright 2013 Agustina Martinez-Garcia

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package uk.ljmu.qudex.qudexservlet.mulgara;

import java.io.OutputStream;

import org.apache.log4j.Logger;
import org.igfay.jfig.JFig;
import org.igfay.jfig.JFigException;

import uk.ljmu.mulgaraifz.errorhandling.MulgaraException;
import uk.ljmu.mulgaraifz.httprequests.HttpManagement;
import uk.ljmu.mulgaraifz.utilities.Constants;
import uk.ljmu.qudex.qudexservlet.queryutils.SparqlConstants;

public class SparqlMulgaraImpl implements ISparqlMulgara {

	private static Logger log = Logger.getLogger(SparqlMulgaraImpl.class);
	/**
	 * 
	 */
	private HttpManagement httpMan;

	/**
	 * Getter for the httpMan object
	 * 
	 * @return httpMan
	 */
	public HttpManagement getHttpMan() {
		return httpMan;
	}

	/**
	 * Default credentials from config file
	 * 
	 * @throws MulgaraException
	 */
	public SparqlMulgaraImpl() throws MulgaraException {
		String basePath;

		try {

			basePath = JFig.getInstance().getValue("mulgaraServer", "service");
			log.debug("Create Mulgara instance, basepath " + basePath);
			this.httpMan = HttpManagement.getInstance();

		} catch (JFigException e) {
			log.error("Error:", e);
			throw new MulgaraException(
					"Unable to initialise parameters from config file, check error log...");
		}
	}

	/**
	 * 
	 * @param user
	 *            mulgara user
	 * @param password
	 *            mulgara passwd
	 * @throws MulgaraException
	 */
	public SparqlMulgaraImpl(String user, String password)
			throws MulgaraException {
		
		// TODO IMPLEMENT ACCESS TO CREDENTIALS
		this.httpMan = HttpManagement.getInstance();
	}

	/**
	 * 
	 * @param collectionId
	 * @return
	 * @throws MulgaraException 
	 */
	public void generateCollectionsJsonFile(String collectionId, OutputStream out) throws MulgaraException {
		
		String constantValue;
		String query = SparqlConstants.GET_ALL_COLLECTIONS_MOD;

		constantValue = JFig.getInstance().getValue("mulgaraServer", "GRAPH",
			HttpManagement.DEFAULT_GRAPH);
		if (!constantValue.startsWith(Constants.ID_SEP_OPEN))
		    constantValue = Constants.ID_SEP_OPEN + constantValue
			    + Constants.ID_SEP_CLOSE;
		
		// Include Mulgara URI from configuration parameters
		query = SparqlConstants.parseQuery(query, "GRAPH", constantValue);
		// Include Collections prefix from Constants
		query = SparqlConstants.parseQuery(query, "COL_PREFIX", SparqlConstants.COL_PREFIX);
		// Specify the format of the results to Mulgara query, in this case JSON
		String format = JFig.getInstance().getValue("mulgaraServer", "output",
				SparqlConstants.SPARQL_JSON);
		// Include collection id from the user input
		query = SparqlConstants.parseQuery(query, "COL_ID", collectionId);
		// Query Mulgara
		//strBody = httpMan.httpSparqlQueryToFile("/Users/agustina/Sites/test-qudex/json-test1/documents.json", query, format);
		httpMan.httpSparqlQueryToOutput(query, format, out);
	}

	/**
	 * 
	 * @param collectionId
	 * @return
	 * @throws MulgaraException 
	 */
	public void generateDocumentsJsonFile(String collectionId, OutputStream out) throws MulgaraException {
		String constantValue;
		String query = SparqlConstants.GET_DOCUMENTS_BY_COLLECTION;

		constantValue = JFig.getInstance().getValue("mulgaraServer", "GRAPH",
			HttpManagement.DEFAULT_GRAPH);
		if (!constantValue.startsWith(Constants.ID_SEP_OPEN))
		    constantValue = Constants.ID_SEP_OPEN + constantValue
			    + Constants.ID_SEP_CLOSE;
		
		// Include Mulgara URI from configuration parameters
		query = SparqlConstants.parseQuery(query, "GRAPH", constantValue);
		// Include Collections prefix from Constants
		query = SparqlConstants.parseQuery(query, "COL_PREFIX", SparqlConstants.COL_PREFIX);
		//Include Fedora server path to provide access to the data in the repository
		String server = JFig.getInstance().getValue("mulgaraServer", "fedoraServer",
				SparqlConstants.DEFAULT_FEDORA_SERVER);
		query = SparqlConstants.parseQuery(query, "FEDORA_SERVER", server);
		// Specify the format of the results to Mulgara query, in this case JSON
		String format = JFig.getInstance().getValue("mulgaraServer", "output",
				SparqlConstants.SPARQL_JSON);
		// Include collection id from the user input
		query = SparqlConstants.parseQuery(query, "COL_ID", collectionId);
		// Query Mulgara
		httpMan.httpSparqlQueryToOutput(query, format, out);
	}

	/**
	 * 
	 * @param collectionId
	 * @return
	 * @throws MulgaraException 
	 */
	public void generateCategoriesJsonFile(String collectionId, OutputStream out) throws MulgaraException {
		String constantValue;
		String query = SparqlConstants.GET_CATEGORIES_BY_COLLECTION;

		constantValue = JFig.getInstance().getValue("mulgaraServer", "GRAPH",
			HttpManagement.DEFAULT_GRAPH);
		if (!constantValue.startsWith(Constants.ID_SEP_OPEN))
		    constantValue = Constants.ID_SEP_OPEN + constantValue
			    + Constants.ID_SEP_CLOSE;
		
		// Include Mulgara URI from configuration parameters
		query = SparqlConstants.parseQuery(query, "GRAPH", constantValue);
		// Include Collections prefix from Constants
		query = SparqlConstants.parseQuery(query, "COL_PREFIX", SparqlConstants.COL_PREFIX);
		// Specify the format of the results to Mulgara query, in this case JSON
		String format = JFig.getInstance().getValue("mulgaraServer", "output",
				SparqlConstants.SPARQL_JSON);
		// Include collection id from the user input
		query = SparqlConstants.parseQuery(query, "COL_ID", collectionId);
		// Query Mulgara
		httpMan.httpSparqlQueryToOutput(query, format, out);
	}

}
